package org.android.bbdroid;

import org.android.bbdroid.guiutils.Alerts;
import org.android.bbdroid.guiutils.Alerts.AlertsInputBoolean;
import org.android.bbdroid.guiutils.Alerts.AlertsInputOnClickListener;
import org.android.bbdroid.guiutils.Alerts.AlertsInputString;
import org.android.bbdroid.storage.BBDroidPreferences;
import org.android.bbdroid.storage.BBDroidUris;
import org.android.bbdroid.webservice.PHPBBClient;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class BBDroidLoginActivity extends Activity {
	private CharSequence getSelectedUrl() {
		View v = ((Spinner) findViewById(org.android.bbdroid.R.id.spinForum))
				.getSelectedView();
		if (v == null)
			return null;
		TextView tvForum = ((TextView) v
				.findViewById(org.android.bbdroid.R.id.tvForumUrl));
		return tvForum.getText();
	}

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(org.android.bbdroid.R.layout.login);

		((Button) findViewById(org.android.bbdroid.R.id.btnLogin))
				.setOnClickListener(new OnClickLoginListener());
		((Button) findViewById(org.android.bbdroid.R.id.btnAccessNoLogin))
				.setOnClickListener(new OnClickNoLoginListener());

		Spinner spinner = (Spinner) findViewById(org.android.bbdroid.R.id.spinForum);
		Cursor cursor = BBDroidPreferences.getInstance()
				.getForumPreferencesCursor(this);
		String[] columns = new String[] { BBDroidUris.ForumsColums.FORUM_NAME,
				BBDroidUris.ForumsColums.FORUM_URL };
		int[] ids = new int[] { org.android.bbdroid.R.id.tvForumName,
				org.android.bbdroid.R.id.tvForumUrl };
		spinner.setAdapter(new SimpleCursorAdapter(this,
				org.android.bbdroid.R.layout.forum_preference, cursor, columns,
				ids));
	}

	@Override
	protected Dialog onCreateDialog(int paramInt, Bundle paramBundle) {
		return Alerts.onCreateDialog(this, paramInt, paramBundle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu paramMenu) {
		getMenuInflater().inflate(org.android.bbdroid.R.menu.login_menu,
				paramMenu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem paramMenuItem) {
		switch (paramMenuItem.getItemId()) {
		case org.android.bbdroid.R.id.add_forum_menu:

			int[] texts = new int[] {
					org.android.bbdroid.R.string.forum_name_label_text,
					org.android.bbdroid.R.string.forum_address_label_text };
			AlertsInputOnClickListener<AlertsInputString> l = new Alerts.AlertsInputOnClickListener<AlertsInputString>() {
				public void onClick(DialogInterface paramDialogInterface,
						int which) {
					if (which != DialogInterface.BUTTON_POSITIVE)
						return;

					Alerts.AlertsInputString input = getInput();
					String name = input.get(0);
					String url = input.get(1);
					if ((TextUtils.isEmpty(name)) || (TextUtils.isEmpty(url))) {
						Toast.makeText(BBDroidLoginActivity.this,
								org.android.bbdroid.R.string.empty_fields_text,
								Toast.LENGTH_LONG).show();
						return;
					}
					BBDroidPreferences.getInstance().addForumPreference(
							BBDroidLoginActivity.this, name, url);
					Toast.makeText(BBDroidLoginActivity.this,
							org.android.bbdroid.R.string.forum_added_text,
							Toast.LENGTH_LONG).show();
				}
			};
			Alerts.input(this, org.android.bbdroid.R.string.add_forum_text,
					android.R.drawable.ic_dialog_info, l, texts);
			return true;
		case org.android.bbdroid.R.id.delete_forum_menu:

			final BBDroidPreferences.ForumPreference[] preferences = BBDroidPreferences
					.getInstance().getForumPreferences(this);
			String[] preferencesText = new String[preferences.length];
			for (int i = 0; i < preferencesText.length; i++) {
				preferencesText[i] = (preferences[i].getName() + "\n("
						+ preferences[i].getUrl() + ")");
			}

			Alerts.mchoice(
					this,
					org.android.bbdroid.R.string.select_forum_to_delete_text,
					android.R.drawable.ic_dialog_alert,
					preferencesText,
					null,
					null,
					new Alerts.AlertsInputOnClickListener<AlertsInputBoolean>() {
						public void onClick(
								DialogInterface paramDialogInterface, int which) {
							if (which != DialogInterface.BUTTON_POSITIVE)
								return;

							Alerts.AlertsInputBoolean input = getInput();
							for (int i = 0; i < input.size(); i++) {
								if (input.get(i))
									BBDroidPreferences.getInstance()
											.removeForumPreferences(
													BBDroidLoginActivity.this,
													preferences[i].getId());
							}

						}
					});

			Toast.makeText(BBDroidLoginActivity.this,
					org.android.bbdroid.R.string.forums_removed_text,
					Toast.LENGTH_LONG).show();
			return true;
		default:
			return super.onOptionsItemSelected(paramMenuItem);
		}
	}

	private class OnClickLoginListener implements View.OnClickListener {
		private OnClickLoginListener() {}

		public void onClick(View paramView) {
			EditText etUsername = (EditText) BBDroidLoginActivity.this
					.findViewById(org.android.bbdroid.R.id.etUsername);
			EditText etPassword = (EditText) BBDroidLoginActivity.this
					.findViewById(org.android.bbdroid.R.id.etPassword);
			
			final ProgressDialog dlg=Alerts.prog(BBDroidLoginActivity.this,
				org.android.bbdroid.R.string.login_progress_title_text,
					org.android.bbdroid.R.string.login_progress_text,true);
			
			CharSequence seq=BBDroidLoginActivity.this.getSelectedUrl();
			String url = seq==null? null : seq.toString();
			
			new AsyncTask<String, Void, Boolean>(){

				@Override
				protected Boolean doInBackground(String... params) {
					PHPBBClient client = PHPBBClient
							.createInstance(params[2]);
					
					return (client != null) && (client.login(params[0], params[1]) != null);				
				}
				@Override
				protected void onPostExecute(Boolean result){
					dlg.dismiss();
					if(!result){
						Alerts.w(BBDroidLoginActivity.this, 
								org.android.bbdroid.R.string.login_error_title_text, 
								org.android.bbdroid.R.string.login_error_message_text);
						return;
					}
					Intent i = new Intent(BBDroidLoginActivity.this,
							BBDroidForumActivity.class);
					BBDroidLoginActivity.this.finish();
					BBDroidLoginActivity.this.startActivity(i);
					
				}
				
			}
			.execute(etUsername.getText()
							.toString(), etPassword.getText().toString(),
							url);
			

		}
	}

	private class OnClickNoLoginListener implements View.OnClickListener {
		private OnClickNoLoginListener() {}

		public void onClick(View paramView) {
			
			final ProgressDialog dlg=Alerts.prog(BBDroidLoginActivity.this,
					org.android.bbdroid.R.string.login_progress_title_text,
					org.android.bbdroid.R.string.login_progress_text,true);
			
			CharSequence seq=BBDroidLoginActivity.this.getSelectedUrl();
			String url = seq==null? null : seq.toString();
			
			new AsyncTask<String,Void,Boolean>(){

				@Override
				protected Boolean doInBackground(String... params) {
					PHPBBClient client = PHPBBClient
							.createInstance(params[0]);
					return client!=null;
				}
				
				@Override
				protected void onPostExecute(Boolean result){
					dlg.dismiss();
					if(!result){
						Alerts.w(BBDroidLoginActivity.this, 
								org.android.bbdroid.R.string.login_error_title_text, 
								org.android.bbdroid.R.string.login_error_message_text);
						return;
					}
					Intent i = new Intent(BBDroidLoginActivity.this,
							BBDroidForumActivity.class);
					BBDroidLoginActivity.this.finish();
					BBDroidLoginActivity.this.startActivity(i);				}
				
			}
			.execute(url);
			
			
		}
	}
}